#!/usr/bin/env python
# coding=utf-8
#----------------------------------------------------------------------------
# 文件名：      price.py
# 说明：       更新个股的价格
# 作者：       fern
# 创建时间：    2015-4-21
# 版权：       (c) 2015 by fern
# 许可证：      apache license
#----------------------------------------------------------------------------
import mysqlDB
import hashlib,re,sys
from bs4 import BeautifulSoup
from  datetime  import  *
import gzip,urllib2,random,time
import urllib
import StringIO
import json
import traceback
import socket
socket.setdefaulttimeout(10)
reload(sys)
sys.setdefaultencoding('utf-8')

class Price:
    def __init__(self):
        self.db =mysqlDB.Mydb(host='localhost', dataBase='stock', user='root', passwd='123456')
        self.db.dbLoad()

    def price(self):
        now=datetime.now()
        date=now.strftime('%Y-%m-%d')
        time=now.strftime('%H:%M:%S')
        sql="SELECT * FROM  `stock` WHERE `price`<>'%s' or `price`='0';" % date
        query=self.db.query(sql)
        for row in query:
            url='http://apistore.baidu.com/microservice/stock?stockid=%s' % row['code']
            html=self.get_html(url)
            if html:
                js=json.loads(html)
                self.update(row['code'],js,date)

    def update(self,code,js,date):
        if js['errNum']==0:
            st=js['retData']
            info=st['stockinfo']
            kl=st['klinegraph']
            sql="UPDATE  `stock` SET  `currentPrice` =  '%s'" % info['currentPrice']
            sql+=" WHERE `code`='%s';" % code
            self.db.save(sql)
            #print sql
            price='INSERT INTO `price`(`code`, `OpenningPrice`, `closingPrice`, `currentPrice`, `hPrice`, `lPrice`, `competitivePrice`, `auctionPrice`, `totalNumber`, `turnover`, `date`, `time`) VALUES '
            price+="('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (info['code'],info['OpenningPrice'],info['closingPrice'],info['currentPrice'],info['hPrice'],info['lPrice'],info['competitivePrice'],info['auctionPrice'],info['totalNumber'],info['turnover'],info['date'],info['time'])
            self.db.save(price)
            self.update_stock(info['code'],'price',date)
            #print price
            print "更新成功%s : %s \n\r" % (info['code'],info['name'])
        else:
            print js['errNum']

    def update_stock(self,code,filed,date):
        sql="UPDATE `stock` SET  `%s`='%s' WHERE `code`='%s';" % (filed,date,code)
        self.db.save(sql)

    def get_gzip(self,url,num=0):
        if num==None:
            num=0
        elif num>3:
            return False
        header = {'Accept-Charset':'GBK,utf-8;q=0.7,*;q=0.3','User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16'}
        request = urllib2.Request(url,headers=header)
        request.add_header('Accept-encoding', 'gzip')
        opener = urllib2.build_opener()
        try:
            f = opener.open(request,timeout=10)
            isGzip = f.headers.get('Content-Encoding')
            if isGzip :
                compresseddata = f.read()
                compressedstream = StringIO.StringIO(compresseddata)
                gzipper = gzip.GzipFile(fileobj=compressedstream)
                data = gzipper.read()
            else:
                data = f.read()
            return data
        except:
            traceback.print_exc()
            if num<3:
                num=num+1
                self.get_gzip(url,num)

    def get_html(self,url,num=0):
        if num==None:
            num=0
        elif num>3:
            return False
        try:
            if url != None:
                page = urllib.urlopen(url)
                html = page.read()
            else:
                html=""
            return html
        except:
            traceback.print_exc()
            if num<3:
                num=num+1
                self.get_html(url,num)

    def close(self):
        self.db.dbClose()

if __name__ == '__main__':
    print "Prepare data. is come soon ..."
    price=Price()
    price.price()
    price.close()
